<!--
 * @Date: 2025-01-16 09:55:20
 * @Author: LiSong
 * @LastEditors: ZHM
 * @LastEditTime: 2025-01-22 11:20:39
 * @Description: 主页授权
-->
<template>
  <div class="home-auth-wrapper">
    <el-tabs style="height: 100%;" v-model="tabState.activeName" type="border-card">
      <el-tab-pane
        v-for="item in tabPanels"
        :key="item.name"
        :name="item.name"
        :label="item.label"
        >
        <component
          :ref="(el) => { compRefs[item.name] = el }"
          :is="item.component"
          @auth="handleDrawerOpen"
        >
        </component>
      </el-tab-pane>
    </el-tabs>
    <!-- 弹窗抽屉 -->
    <el-drawer
      :="drawerAttrs"
      @close="handleDrawerClose"
      v-model="drawerState.visible"
    >
      <div class="home-drawer-wrapper">
        <div class="drawer-content">
          <HomePanel ref="homePanelRef" />
        </div>
        <div class="drawer-footer">
          <el-button type="primary" @click="handleDrawerConfirm">保存</el-button>
          <el-button @click="handleDrawerClose">取消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, reactive } from 'vue';
import { defAxios } from '@/utils/http'
import { ElMessage } from 'element-plus';
import { RkConfirmBox } from '@/components/message-box'

import RoleTable from './table/RoleTable.vue'
import UserTable from './table/UserTable.vue'
import HomePanel from './panel/HomePanel.vue'

// 标签组件的数据集
const tabState = reactive({
  activeName: 'role'
})
// 标签面板的配置信息
const tabPanels = [
  { label: '角色', name: 'role', type: "1", component: RoleTable },
  { label: '用户', name: 'user', type: "2", component: UserTable },
]
const tabPanelItem = computed(() => {
  return tabPanels.find(item => item.name == tabState.activeName)
})

// 动态组件的Ref集
const compRefs = ref({})
// 主页表格的Ref
const homePanelRef = ref()
// 抽屉面板属性配置
const drawerAttrs = reactive({
  size: '60%',
  title: '选择关联主页',
  zIndex: 1000,
  showClose: true,
  withHeader: true,
  appendToBody: true,
  closeOnPressEscape: false,
})
// 抽屉面板数据集
const drawerState = reactive({
  visible: false,
  loading: false,
})
/**
 * 打开抽屉的方法
 */
const handleDrawerOpen = () => {
  const compRef = compRefs.value[tabState.activeName]
  const checkData = compRef.getCheckedData()
  if (checkData && checkData.length === 0) {
    ElMessage.warning(`请选择需要授权的${ tabPanelItem.value.label }！`)
    return
  }
  drawerState.visible = true
}
/**
 * 抽屉组件中确定按钮点击的方法
 */
const handleDrawerConfirm = async () => {
  if (drawerState.loading) return
  
  // 当前的加载的动态组件的Ref
  const compRef = compRefs.value[tabState.activeName]
  // 获取选中主页数据
  const checkData = homePanelRef.value.getCheckedData()
  // 获取选中的角色或用户数据
  const busiData = compRef.getCheckedData()
  const busiHome = busiData.map(item => item.homeName).filter(item => !!item)
  if (!checkData) {
    if (busiHome.length === 0) {
      ElMessage.warning(`请选择一条数据进行操作！`)
      return
    }
    RkConfirmBox({
      title: '提示',
      content: `未选择关联主页，继续将取消所选${ tabPanelItem.value.label }数据的主页授权，是否继续！`,
      confirmButtonText: '是',
      cancelButtonText: '否',
      onSubmit: function () {
        saveRoleUserRelateHome(checkData, busiData)
      },
      onCancel: function () {},
      }
    )
  } else {

    if (busiHome.length > 0) {
      RkConfirmBox({
      title: '提示',
      content: `所选${ tabPanelItem.value.label }数据中已存在关联主页，继续将覆盖原有主页，是否继续！`,
      confirmButtonText: '是',
      cancelButtonText: '否',
      onSubmit: function () {
        saveRoleUserRelateHome(checkData, busiData)
      },
      onCancel: function () {},
      }
    )
    } else {
      saveRoleUserRelateHome(checkData, busiData)
    }
  }
}
/**
 * 抽屉组件关闭操作
 */
const handleDrawerClose = () => {
  homePanelRef.value.clearCheckedData()
  drawerState.visible = false
}

/**
 * 保存用户或角色关联的主页信息（为空则表示清空）
 * 
 * @param checkData 选择的主页数据
 */
const saveRoleUserRelateHome = async (checkData, busiData) => {
  drawerState.loading = true
  // 当前的加载的动态组件的Ref
  const compRef = compRefs.value[tabState.activeName]
  // 封装数据
  const params = {
    homeId: checkData ? checkData.formId : '',
    businessType: tabPanelItem.value.type,
    businessIdList: busiData.map(item => item.guid),
  }
  const flag = await reqSaveRoleUserRelateHome(params)
  drawerState.loading = false
  if (!flag) return
  compRef.handleTableSearch()
  handleDrawerClose()
}

/**
 * 请求保存用户或角色关联的主页信息（为空则表示清空）
 * 
 * @param params 参数数据
 */
const reqSaveRoleUserRelateHome = (params) => {
  return new Promise(resolve => {
    defAxios({
      url: '/userRoleHome/saveUserRoleHome',
      data: params,
      method: 'post'
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('操作成功！')
        resolve(true)
      } else {
        ElMessage.success(res.msg)
        console.error(res.msg)
        resolve(false)
      }
    }).catch((err) => {
      ElMessage.success('操作失败！')
      console.error(err)
      resolve(false) 
    })
  })
}

</script>

<style lang="scss" scoped>
.home-auth-wrapper {
  padding: 8px;
  height: 100%;
  position: relative;
}
.tab-head-tool {
  position: absolute;
  z-index: 99;
  right: 17px;
  top: 13px;
}
.home-drawer-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  .drawer-content {
    flex: 1;
    // padding: 8px;
    padding-top: 0;
    min-height: 100px;
  }
  .drawer-footer {
    padding: 0 15px !important;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top: 1px solid var(--el-border-color);
    color: var(--el-text-color-primary);
  }
}
:deep(.el-tabs) {
  height: 100%;
  display: flex;
  position: relative;
  .el-tabs__content {
    flex: 1;
    padding: 0;
    .el-tab-pane {
      height: 100%;
    }
  }
}
</style>